<?php
namespace App\Http\Controllers\Api\Mall;

use App\Http\Controllers\Api\Third\WechatController;
use App\Http\Controllers\Controller;
use App\Order;
use App\OrderItem;
use App\Products;
use App\UserCoin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class PayController extends Controller
{
    const business_id = 7;  //商城

    protected $request;

    /**
     * @function 商品兑换
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function exchange(Request $request)
    {
        $this->request = $request;
        $products_id = $request->input('products_id');
        $pay_type = $request->input('pay_type');//支付类型  1.金币  2.微信支付
        $type = $request->input('type', 'JSAPI');
        $user = auth()->user();

        //支付类型
        $type_pay_arr = [
            1 => 1,
            2 => 2,
        ];
        if (!in_array($pay_type, $type_pay_arr)) {
            return $this->genRet(1002, '非法支付方式');
        }

        $products = Products::findOrFail($products_id);
        //判断商品上下架
        if (!$products->on_sale) {
            return $this->genRet(1002, '商品已下架');
        }
        $order_id = date('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);

        try {
            DB::beginTransaction();

            $quantity = 1; //兑换一个
            $jb = $products->need_jb / 100 * $quantity;
            $userTotalJb = UserCoin::totalJb($user->id);

            $order = new Order();
            $order->trade_id = $order_id;
            $order->user_id = $user->id;
            $order->status = 0;
            $order->ukey = $order_id;
            $order->save();

            //支付方式
            switch ($pay_type) {
                case 1://金币
                    if ($jb < 0) {
                        DB::rollBack();
                        return $this->genRet(1002, '金币错误');
                    }
                    if ($userTotalJb < $jb) {
                        DB::rollBack();
                        return $this->genRet(1002, '金币不够兑换');
                    }
                    //先扣除用户金币，一个用户一秒不能重复兑换多次
                    $key = self::business_id . '-' . UserCoin::TYPE_JB . '-' . $user->id . '-' . time();
                    UserCoin::log(self::business_id, $user->id, UserCoin::TYPE_JB, -$jb, '商城金币兑换' . $products->name, $key);
                    break;
                case 2: //微信支付
                    $wechat = new  WechatController();
                    $payData = $wechat->productsPay($user, $order, $products, $type);
                    $payArr = json_decode($payData, true);
                    if ($payArr['code'] != 1000) {
                        DB::rollBack();
                        return $this->genRet(1002, '创建订单失败！');
                    }
                    break;
                default:
                    DB::rollBack();
                    return $this->genRet(1002, '非法支付方式');
                    break;
            }

            $orderItem = new OrderItem();
            $orderItem->order_id = $order->id;
            $orderItem->products_id = $products_id;
            $orderItem->price = $products->price;
            $orderItem->original_price = $products->original_price;
            $orderItem->product_name = $products->name;
            $orderItem->thumbnail = $products->thumbnail;
            $orderItem->quantity = $quantity;
            $orderItem->jb = $products->need_jb;
            $orderItem->save();

            switch ($pay_type) {
                case 1:
                case 2:
                    //再判断用户总金币是否小于0，小于的时候回滚
                    if ($pay_type == 1) {
                        $userTotalJb = UserCoin::totalJb($user->id);
                        if ($userTotalJb < 0) {
                            DB::rollBack();
                            return $this->genRet(1002, '金币不够兑换');
                        }
                    }
                    break;
                case 3:
                    break;
            }

            if ($pay_type == 1) {
                $order->status = 1;
                $order->save();
                DB::commit();
            }

            if ($pay_type == 2) {
                DB::commit();
                return response()->json($payArr);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->genRet(1003, '网络繁忙，请稍候再试');
        }

        return $this->genRet(1000, '兑换成功');
    }

    /**
     * @function 接口返回信息
     *
     * @param $code
     * @param $msg
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    private function genRet($code, $msg, $data = [])
    {
        return response()->json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }
}